package com.rabbit.videoplayer.widget

import android.content.Context
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import com.rabbit.videoplayer.listener.OnVideoStatusListener
import com.rabbit.videoplayer.R
import com.rabbit.videoplayer.SpeedValue
import com.rabbit.videoplayer.tools.Constants
import com.rabbit.videoplayer.tools.TimeFormater
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import androidx.core.view.isVisible
import com.blankj.utilcode.util.ConvertUtils

class ControlView(context: Context, attrs: AttributeSet? = null) : RelativeLayout(context, attrs), OnClickListener, OnVideoStatusListener {

    private val btnBack: View
    private val btnCastScreen: View
    private val btnUnlock: ImageView
    private val btnPlay: View
    private val btnPlayNext: View
    private val btnSpeed: TextView
    private val btnScale: TextView
    private val btnEpisode: TextView
    private val btnFullScreen: View
    private val tvVideoSource: TextView
    private val tvVideoTitle: TextView
    private val tvCurrentPosition: TextView
    private val tvDuration: TextView
    private val tvVideoTime: TextView
    private val ivPlay: ImageView
    private val ivFullScreen: ImageView
    private val seekBar: SeekBar
    private val layoutTop: View
    private val layoutBottom: View
    private val tvComplete: TextView
    private val layoutComplete: View
    private val layoutSeekHistory: View
    private val tvSeekHistory: TextView
    private val layoutSeekBar: View
    private val layoutTopSeekbar: View
    private val tvTopSeekStartTime: TextView
    private val tvTopSeekEndTime: TextView
    private val topSeekBar: SeekBar

    // 剧集总数
    private var episodeCount = 0
    // 当前播放的剧集index
    private var currentPlayIndex = 0
    // 视频当前的播放进度
    private var currentPosition = 0L
    // 当前屏幕的缩放方式
    private var scaleMode = Constants.VIDEO_RESIZE_FIT
    // 当前是否正在触摸进度条
    var isSeekBarOnTouch = false
    // 视频是否处于prepared状态
    private var isPrepared = false
    // 是否全屏，默认非全屏
    private var isFullScreen = false
    // 是否锁屏，默认未上锁
    private var isLockScreen = false
    // 是否显示下一集按钮
    private var isShowPlayNext = true
    // 是否显示播放历史提示
    private var isShowHistorySeek = false
    // 显示当前时间的handler
    private var timeHandler:TimeHandler? =null
    // 控制器回调
    private var callback: OnControlClickCallback? = null

    // 当前时间timer
    class TimeHandler(private val tvSysTime: TextView,
                      private val tvSeekHistory: TextView,
                      private val tvComplete: TextView
    ): android.os.Handler(Looper.getMainLooper()){
        private var callback: OnControlClickCallback? = null
        private val sdf = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
        fun setControlClickCallback(callback: OnControlClickCallback?) {
            this.callback = callback
        }
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what){
                0 -> { // 系统时间
                    val data = Date()
                    tvSysTime.text = sdf.format(data)
                    sendEmptyMessageDelayed(0, 1000)
                }
                1 -> { // 历史播放提醒
                    tvSeekHistory.visibility = View.GONE
                }

                2 -> { // 播放下一集提示
                    if (msg.arg1 <= 0) {
                        callback?.playNext()
                    } else {
                        tvComplete.text = String.format(Locale.getDefault(), "%ds后，即将播放下一集~", msg.arg1)
                        val newMsg = obtainMessage()
                        newMsg.what = 2
                        newMsg.arg1 = msg.arg1 - 1
                        sendMessageDelayed(newMsg, 1000)
                    }
                }
            }

        }
    }

    init {
        val rootView = LayoutInflater.from(context).inflate(R.layout.view_wb_mix_video_control, this, true)
        btnBack = rootView.findViewById(R.id.layout_video_back)
        btnCastScreen = rootView.findViewById(R.id.layout_screen)
        btnUnlock = rootView.findViewById(R.id.iv_video_lock)
        btnPlay = rootView.findViewById(R.id.layout_video_play)
        btnPlayNext = rootView.findViewById(R.id.layout_video_play_next)
        btnScale = rootView.findViewById(R.id.tv_video_scale)
        btnEpisode = rootView.findViewById(R.id.tv_video_episode)
        btnSpeed = rootView.findViewById(R.id.tv_video_speed)
        btnFullScreen = rootView.findViewById(R.id.layout_full_screen)

        ivPlay = rootView.findViewById(R.id.iv_video_play)
        ivFullScreen = rootView.findViewById(R.id.iv_video_full_screen)

        tvVideoTitle = rootView.findViewById(R.id.tv_video_title)
        tvCurrentPosition = rootView.findViewById(R.id.tv_video_current_position)
        tvDuration = rootView.findViewById(R.id.tv_video_duration)
        tvVideoTime = rootView.findViewById(R.id.tv_video_time)
        tvComplete = rootView.findViewById(R.id.tv_play_complete)
        tvSeekHistory = rootView.findViewById(R.id.tv_seek_history)
        tvVideoSource = rootView.findViewById(R.id.tv_video_source)

        seekBar = rootView.findViewById(R.id.sb_video_bottom)

        layoutTop = rootView.findViewById(R.id.layout_video_title)
        layoutBottom = rootView.findViewById(R.id.layout_bottom_control)
        layoutComplete = rootView.findViewById(R.id.layout_play_complete)
        layoutSeekHistory = rootView.findViewById(R.id.layout_seek_to)

        layoutSeekBar = rootView.findViewById(R.id.layout_control_Seekbar)
        layoutTopSeekbar = rootView.findViewById(R.id.layout_top_seekbar)
        tvTopSeekStartTime = rootView.findViewById(R.id.tv_top_video_current_position)
        tvTopSeekEndTime = rootView.findViewById(R.id.tv_top_video_duration)
        topSeekBar = rootView.findViewById(R.id.sb_top_video_bottom)


        btnBack.setOnClickListener(this)
        btnPlay.setOnClickListener(this)
        btnSpeed.setOnClickListener(this)
        btnScale.setOnClickListener(this)
        btnUnlock.setOnClickListener(this)
        btnCastScreen.setOnClickListener(this)
        btnEpisode.setOnClickListener(this)
        btnPlayNext.setOnClickListener(this)
        btnFullScreen.setOnClickListener(this)
        tvVideoSource.setOnClickListener(this)

        topSeekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    // 修改当前进度文本
                    val realProgress = progress * 1000L
                    setCurrentPosition(realProgress, true)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isSeekBarOnTouch = true
                callback?.isStartTrackingTouch(true)
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isSeekBarOnTouch = false
                callback?.isStartTrackingTouch(false)
                // 返回告诉播放器当前的进度
                // 修改当前进度文本
                val realProgress = (seekBar?.progress ?: 0) * 1000L
                callback?.seekTo(realProgress)
            }
        })

        seekBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {

            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    // 修改当前进度文本
                    val realProgress = progress * 1000L
                    setCurrentPosition(realProgress, true)
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                isSeekBarOnTouch = true
                callback?.isStartTrackingTouch(true)
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                isSeekBarOnTouch = false
                callback?.isStartTrackingTouch(false)
                // 返回告诉播放器当前的进度
                // 修改当前进度文本
                val realProgress = (seekBar?.progress ?: 0) * 1000L
                callback?.seekTo(realProgress)
            }
        })

        timeHandler = TimeHandler(tvVideoTime, tvSeekHistory, tvComplete)
    }

    /**
     * 设置视频名称
     * @param title 视频名称
     */
    fun setVideoTitle(title: String?) {
        tvVideoTitle.text = title ?: ""
    }


    // 是否是全屏状态
    private var isFullScreenStatus = false
    /**
     * 隐藏全屏按钮
     */
    fun hideFullScreenButton(){
        isFullScreenStatus = true
        btnFullScreen.visibility = View.GONE
    }

    fun setSourceName(name: String) {
        tvVideoSource.text = name
    }

    /**
     * 是否显示播放下一集按钮
     * @param isShow
     */
    fun setShowPlayNext(isShow: Boolean) {
        this.isShowPlayNext = isShow
        if (isFullScreen) {
            if (isShowPlayNext) {
                btnPlayNext.visibility = View.VISIBLE
            } else {
                btnPlayNext.visibility = View.GONE
            }
        }else {
            btnPlayNext.visibility = View.GONE
        }
    }

    /**
     * 设置视频时长
     * @param duration 视频时长 Long
     */
    fun setDuration(duration: Long) {
        val durationStr = TimeFormater.formatMs(duration)
        tvDuration.text = durationStr
        tvTopSeekEndTime.text = durationStr
        seekBar.max = (duration / 1000).toInt()
        topSeekBar.max = (duration / 1000).toInt()
    }

    /**
     * 设置视频当前播放进度
     * @param currentPosition 视频时长 Long
     */
    fun setCurrentPosition(currentPosition: Long, fromUser: Boolean = false) {
        val currentPositionStr = TimeFormater.formatMs(currentPosition)
        tvCurrentPosition.text = currentPositionStr
        tvTopSeekStartTime.text = currentPositionStr
        if (!fromUser) {
            seekBar.progress = (currentPosition / 1000).toInt()
            topSeekBar.progress = (currentPosition / 1000).toInt()
        }

    }

    /**
     * 设置视频当前播放进度
     * @param bufferedPosition 视频时长 Long
     */
    fun setBufferedPosition(bufferedPosition: Long) {
        seekBar.secondaryProgress = (bufferedPosition / 1000).toInt()
        topSeekBar.secondaryProgress = (bufferedPosition / 1000).toInt()
    }

    override fun onClick(v: View?) {
        when (v) {
            btnBack -> callback?.onBack()
            btnSpeed -> {
                if (!isPrepared) return
                callback?.showMore()
            }

            btnScale -> {
                if (!isPrepared) return
                callback?.showMore()
            }

            btnEpisode -> {
                if (!isPrepared) return
                // 显示剧集列表
                callback?.showEpisodeList()
            }

            btnPlayNext -> {
                if (!isPrepared) return
                callback?.playNext()
            }

            btnPlay -> {
                if (!isPrepared) return
                callback?.switchPlay()
            }

            btnUnlock -> {
                if (!isPrepared) return
                isLockScreen = !isLockScreen
                callback?.switchLock(isLockScreen)
            }

            btnFullScreen -> {
                if (!isPrepared) return
                isFullScreen = !isFullScreen
                callback?.switchFullScreen(isFullScreen)
            }

            btnCastScreen -> {
                if (!isPrepared) return
                callback?.castScreen()
            }

            tvVideoSource -> {
                callback?.changeSource()
            }

            else -> {}
        }
    }

    interface OnControlClickCallback {
        /**
         * 返回
         */
        fun onBack()

        /**
         * 通过点击倍速或缩放显示操作框
         */
        fun showMore()

        /**
         * 显示剧集列表
         */
        fun showEpisodeList()

        /**
         * 切换剧集
         */
        fun playNext(): Boolean

        /**
         * 切换播放状态
         * @return true: 播放，false: 暂停
         */
        fun switchPlay()

        /**
         * 解锁或锁屏
         */
        fun switchLock(isLockedScreen: Boolean)

        /**
         * 全屏或缩小
         */
        fun switchFullScreen(isFullScreen: Boolean)

        /**
         * 点击投屏
         */
        fun castScreen()

        /**
         * 是否滑动进度条
         * @param isTouchOn true: 按在进度条上，false: 离开进度条
         */
        fun isStartTrackingTouch(isTouchOn: Boolean)

        /**
         * 滑动进度条变化（只有当isStartTrackingTouch的参数为true的时候才有用）
         * @param progress 当前的进度值
         */
        fun seekTo(progress: Long)

        /**
         * 准备切换线路
         */
        fun changeSource()

    }


    // 切换播放状态对应的UI
    private fun switchPlayOrPauseUI(isPlaying: Boolean) {
        if (!isPrepared) return // 防止手贱
        val drawableResId = if (isPlaying) {
            R.drawable.ic_wb_mix_video_pause
        } else {
            R.drawable.ic_wb_mix_video_play
        }
        ivPlay.setBackgroundResource(drawableResId)
    }

    // 切换锁屏状态对应的UI
    private fun switchLockUI(isLocked: Boolean) {
        val drawableResId = if (isLocked) {
            R.drawable.ic_wb_mix_video_screen_lock
        } else {
            R.drawable.ic_wb_mix_video_screen_unlock
        }
        btnUnlock.setBackgroundResource(drawableResId)

        if (isLocked) {
            tvVideoTime.visibility = View.GONE
            layoutTop.visibility = View.GONE
            layoutBottom.visibility = View.GONE
            layoutTopSeekbar.visibility = View.GONE
        } else {
            layoutTop.visibility = View.VISIBLE
            layoutBottom.visibility = View.VISIBLE
            if (isFullScreen) {
                layoutTopSeekbar.visibility = View.VISIBLE
                tvVideoTime.visibility = View.VISIBLE
            } else {
                tvVideoTime.visibility = View.GONE
                layoutTopSeekbar.visibility = View.GONE
            }
        }
    }

    // 切换锁屏状态对应的UI
    private fun switchFullScreenUI(isFullScreen: Boolean) {
        this.isFullScreen = isFullScreen
        val drawableResId = if (isFullScreen) {
            R.drawable.ic_wb_mix_video_zoom
        } else {
            R.drawable.ic_wb_mix_video_full_screen
        }
        ivFullScreen.setBackgroundResource(drawableResId)
        if (isFullScreen) {
            startSystemTime()
            btnCastScreen.visibility = View.GONE
            tvVideoTime.visibility = View.VISIBLE
            btnUnlock.visibility = View.VISIBLE
            if (isFullScreenStatus || isSkitsVideo) { // 播放下载视频和短剧的时候，不显示线路
                tvVideoSource.visibility = View.GONE
            } else {
                if (isDisplaySourceSwitch) {
                    tvVideoSource.visibility = View.VISIBLE
                }
            }

            btnSpeed.visibility = View.VISIBLE
            btnScale.visibility = View.VISIBLE
            btnEpisode.visibility = View.VISIBLE
            // 解锁需要更多条件
            btnPlayNext.visibility = if (isShowPlayNext) View.VISIBLE else View.GONE

            layoutTopSeekbar.visibility = View.VISIBLE
            layoutSeekBar.visibility = View.GONE
            // 设置顶部的padding
            layoutTop.layoutParams.height = resources.getDimension(R.dimen.d_100).toInt()
            layoutTop.setPadding(0, resources.getDimension(R.dimen.d_10).toInt(), 0 ,0)

        } else {
            btnCastScreen.visibility = View.VISIBLE
            tvVideoTime.visibility = View.GONE
            btnUnlock.visibility = View.GONE
            tvVideoSource.visibility = View.GONE
            btnScale.visibility = View.GONE
            btnSpeed.visibility = View.GONE
            btnEpisode.visibility = View.GONE
            btnPlayNext.visibility = View.GONE

            layoutTopSeekbar.visibility = View.GONE
            layoutSeekBar.visibility = View.VISIBLE
            layoutTop.layoutParams.height = resources.getDimension(R.dimen.d_50).toInt()
            layoutTop.setPadding(0, 0, 0 ,0)
        }
    }



    fun setControlClickCallback(callback: OnControlClickCallback?) {
        this.callback = callback
        timeHandler?.setControlClickCallback(callback)
    }

    private fun clearHandlerMessage() {
        timeHandler?.removeMessages(0)
        timeHandler?.removeMessages(1)
        timeHandler?.removeMessages(2)
    }

    fun hide() {
        tvVideoTime.text = ""
        clearHandlerMessage()
        // 所有控件都显示
        this.visibility = View.GONE
        layoutSeekHistory.visibility = View.GONE
    }

    private var isDisplaySourceSwitch: Boolean = true
    fun setFullScreenSourceSwitch(isDisplaySourceSwitch: Boolean){
        this.isDisplaySourceSwitch = isDisplaySourceSwitch
        tvVideoSource.visibility = if (isDisplaySourceSwitch) View.VISIBLE else View.GONE
     }

    fun show() {
        // 所有控件都显示
        this.visibility = View.VISIBLE
        switchLockUI(isLockScreen)
        if (!isLockScreen) {
            // 回复可能因为其他流程导致的部分ui显示不对
            if (layoutTop.visibility != View.VISIBLE) {
                layoutTop.visibility = View.VISIBLE
            }
            if (layoutBottom.visibility != View.VISIBLE) {
                layoutBottom.visibility = View.VISIBLE
            }
            if (isFullScreen && btnUnlock.visibility != View.VISIBLE) {
                btnUnlock.visibility = View.VISIBLE
            }
            if (layoutComplete.visibility != View.GONE) {
                layoutComplete.visibility = View.GONE
            }
            if (isFullScreen) {
                startSystemTime()
            }
        }
        if (isSkitsVideo) {
            btnCastScreen.visibility = View.GONE
        }
    }


    private fun startSystemTime(){
        timeHandler?.removeMessages(0)
        timeHandler?.sendEmptyMessage(0)
    }

    /**
     * 当在屏幕中央横向滑动的时候，显示进度条
     * 此时禁止正常的进度计算，交给横向滑动
     */
    fun showOnlySeekBar(seekTo: Long) {
        show()
        // 停止正常的进度
        isSeekBarOnTouch = true
        btnUnlock.visibility = View.GONE
        layoutTop.visibility = View.GONE
        layoutBottom.visibility = View.VISIBLE
        setCurrentPosition(seekTo)
    }


    /**
     * 回复正常的进度计算，返回当前的进度值
     */
    fun hideOnlySeekBar(): Long {
        isSeekBarOnTouch = false
        return seekBar.progress * 1000L
    }

    fun getCurrentPlayEpisode(): Int {
        return currentPlayIndex
    }

    fun setVideoEpisodeData(currentPosition: Int, episodeCount: Int){
        this.episodeCount = episodeCount
        currentPlayIndex = currentPosition
    }
    override fun onVodInit(vararg init: Any?): Boolean {
        val title = init[0].toString()
        isShowPlayNext = currentPlayIndex < episodeCount - 1 && episodeCount > 1
        // 所有控件都显示
        show()
        // 重置时长
        setDuration(0)
        // 重置当前进度
        setCurrentPosition(0)
        setBufferedPosition(0)
        // 重置解锁状态
        switchLockUI(false)
        // 重置播放状态
        switchPlayOrPauseUI(false)

        layoutSeekHistory.visibility = View.GONE
        // 设置是否显示播放下一个
        setShowPlayNext(isShowPlayNext)
        // 重置全屏状态
        switchFullScreenUI(isFullScreen)
        // 设置标题
        setVideoTitle(title)
        // 隐藏完成页面
        layoutComplete.visibility = View.GONE

        if (isSkitsVideo) {
            btnCastScreen.visibility = View.GONE
        }
        return false
    }

    fun getTitle(): String{
        return tvVideoTitle.text.toString()
    }

    fun getEpisodeCount(): Int {
        return episodeCount
    }



    fun setRadio(model: Int) {
        scaleMode = model
        if (!isPrepared) return
        val mode = when (model) {
            Constants.VIDEO_RESIZE_FIT -> "自适应"
            Constants.VIDEO_RESIZE_169 -> "16:9"
            Constants.VIDEO_RESIZE_43 -> "4:3"
            else -> "平铺"
        }
        btnScale.text = mode
    }

    fun getScaleMode(): Int {
        return scaleMode
    }

    fun setSpeed(speed: SpeedValue) {
        if (!isPrepared) return
        btnSpeed.text = when (speed) {
            SpeedValue.Half -> "0.5X"
            SpeedValue.OneQuartern -> "1.25X"
            SpeedValue.OneHalf -> "1.5X"
            SpeedValue.Twice -> "2X"
            SpeedValue.Third -> "3X"
            else -> "正常"
        }
    }

    fun setSpeed(speed: Float) {
        if (!isPrepared) return
        btnSpeed.text = when (speed) {
            SpeedValue.Half.value -> "0.5X"
            SpeedValue.OneQuartern.value -> "1.25X"
            SpeedValue.OneHalf.value -> "1.5X"
            SpeedValue.Twice.value -> "2X"
            SpeedValue.Third.value -> "3X"
            else -> "正常"
        }
    }


    override fun onVodPrepared(vararg prepared: Any) {
        isPrepared = true
        if (prepared.isEmpty()) return
        currentPosition = prepared[0] as Long
        val duration = prepared[1] as Long
        setDuration(duration)
        setCurrentPosition(currentPosition)
        layoutComplete.visibility = View.GONE
    }

    override fun onVodStart() {
        // 重置播放状态
        switchPlayOrPauseUI(true)
    }


    override fun onVodFirstFrameStart() {
        if (currentPosition > 1000L && !isShowHistorySeek) {
            isShowHistorySeek = true
            layoutSeekHistory.visibility = View.VISIBLE
            tvSeekHistory.text = String.format("上次播放到:%s", TimeFormater.formatMs(currentPosition))
            timeHandler?.removeMessages(1)
            timeHandler?.sendEmptyMessageDelayed(1, 2500)
        }
    }

    override fun onVodSwitchDisplayControlView() {
        if (this.isVisible) {
            hide()
        } else {
            show()
        }
    }

    override fun onVodPause() {
        // 重置播放状态
        switchPlayOrPauseUI(false)
    }

    override fun onVodStop() {
        isPrepared = false
        // 重置播放状态
        switchPlayOrPauseUI(false)
        isShowHistorySeek = false
        hide()
    }

    override fun onVodError(vararg params: Any) {
        isPrepared = false
        isShowHistorySeek = false
        // 重置播放状态
        switchPlayOrPauseUI(false)
        clearHandlerMessage()
    }

    override fun onVodComplete() {
        isPrepared = false
        isShowHistorySeek = false
        hide()
    }

    override fun onVodRelease() {
        isPrepared = false
        isShowHistorySeek = false
        clearHandlerMessage()
    }


    override fun onVodLockedScreen(vararg params: Any) {
        isLockScreen = params[0] as Boolean
        switchLockUI(isLockScreen)
    }

    override fun onVodFullScreen(vararg params: Any) {
        val isFullScreen = params[0] as Boolean
        switchFullScreenUI(isFullScreen)
    }

    override fun onVodLoadingBegin() {

    }

    override fun onVodLoadingProgress(vararg params: Any) {

    }

    override fun onVodLoadingEnd() {

    }

    override fun onVodBackPress(): Boolean {
        if (isFullScreen) { // 全屏需要先变小屏幕
            return true
        }
        return false
    }

    override fun onEpisodeSelected() {
        hide()
    }

    override fun onVodShowUnlockUI(isDisplayUI: Boolean) {
        if (isDisplayUI) {
            hide()
        }
    }

    private var isSkitsVideo = false
    override fun onVodSkits() {
        isSkitsVideo = true
        hideFullScreenButton()
        switchFullScreenUI(false)
        btnCastScreen.visibility = View.GONE
        layoutBottom.setPadding(0, 0, 30, 0)
    }


    fun showCompleteAndReadyToPlayNext() {
        show()
        layoutComplete.visibility = View.VISIBLE
        tvComplete.text = String.format(context.getString(R.string.complete_and_ready_to_play_next), 3)

        timeHandler?.removeMessages(2)
        val msg = timeHandler?.obtainMessage()?:return
        msg.what = 2
        msg.arg1 = 2
        timeHandler?.sendMessageDelayed(msg, 1000)

//        playNextDisposable = RxUtils.interval(0, 3, 1000, 1000) {
//            tvComplete.text = String.format(context.getString(R.string.complete_and_ready_to_play_next), 3 - 1 - it)
//            if (it >= 3 - 1) {
//                callback?.playNext()
//            }
//        }
    }

}